package com.xujianlong.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        FlatMapOperator<String, Tuple2<String, Integer>> wordToOne = dataSource.flatMap((s, collector) -> {
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(Tuple2.of(word, 1));
            }

        });
        AggregateOperator<Tuple2<String, Integer>> sumOperator = wordToOne.groupBy(0).sum(1);

        sumOperator.print();
    }
}
